<template>
  <div class="addgood">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- ---------------------------------------------分割线 -->
      <!-- 警示框 -->
      <el-alert
        center
        title="添加商品信息"
        type="info"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- ---------------------------------------------分割线 -->
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- ---------------------------------------------分割线 -->
      <!-- tab栏 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="tabsBeforeLeave"
          @tab-click="tabsClick"
        >
          <!--------------------------------------------------------分割线 -->
          <!-- 基本信息页面 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item prop="goods_name" label="商品名称">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item prop="goods_price" label="商品价格">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item prop="goods_weight" label="商品重量">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item prop="goods_number" label="商品数量">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <!-- 级联选择器 -->
            <el-form-item prop="goods_cat" label="商品分类">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="goodCateList"
                :props="cascaderProps"
                @change="cascaderHandleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!--------------------------------------------------------分割线 -->
          <!-- 商品动态参数页面 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :key="item.attr_id"
              :label="item.attr_name"
              v-for="item in manyAttrList"
            >
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals" size="small">
                <el-checkbox
                  border
                  :key="index1"
                  :label="item1"
                  v-for="(item1, index1) in item.attr_vals"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!--------------------------------------------------------分割线 -->
          <!-- 商品静态属性页面 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :key="item.attr_id"
              :label="item.attr_name"
              v-for="(item) in onlyAttrList"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!--------------------------------------------------------分割线 -->
          <!-- 商品图片页面 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- 上传图片的组件 -->
            <!-- action代表上传路径 -->
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-preview="upLoadLandlePreview"
              :on-remove="upLoadLandleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="uploadSuccessRespoonse"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!--------------------------------------------------------分割线 -->
          <!-- 富文本编辑器 -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button type="primary" style="margin-top: 15px" @click="addGoods"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!--------------------------------------------------------分割线 -->
    <!-- 商品图片弹出对话框 -->
    <el-dialog title="图片预览" :visible.sync="isPicDialogVisible" width="50%">
      <img :src="preUrl" alt="" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script>
// 导入lodash
import _ from "lodash";
import { getCateList } from "../../network/goods/addGood";
import { getAttrList } from "../../network/goods/addGood";
import { addgood } from "../../network/goods/addGood";
export default {
  name: "AddGood",
  data() {
    return {
      // tab栏和步骤条的绑定数据
      activeIndex: 0,
      //   添加商品的信息表单
      addForm: {
        goods_name: "",
        goods_price: null,
        goods_weight: null,
        goods_number: null,
        // 级联选择器value绑定值
        goods_cat: [],
        // 图片路径
        pics: [],
        // 商品详情
        goods_introduce: "",
        // 商品属性
        attrs: [],
      },
      //添加商品的表单验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          {
            type: "array",
            required: true,
            message: "请输入商品分类",
            trigger: "blur",
          },
        ],
      },

      // ----------------------------------------------------------分割线

      // 基本信息页面
      // 分类列表
      goodCateList: [],
      // 级联选择器
      // 级联选择器选项对应值
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },

      // ----------------------------------------------------------分割线

      //商品动态参数页面
      manyAttrList: [],

      // ----------------------------------------------------------分割线

      //商品静态属性页面
      onlyAttrList: [],
      // ----------------------------------------------------------分割线

      //商品图片上传页面
      uploadUrl: "http://127.0.0.1:8888/api/private/v1/upload",
      // 给请求挂载请求头token
      headersObj: {
        Authorization: sessionStorage.getItem("token"),
      },
      //是否弹出图片预览对话框
      isPicDialogVisible: false,
      // 图片预览的url地址
      preUrl: "",
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 发起分类列表申请
    async getCateList() {
      const res = await getCateList();
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.goodCateList = res.data;
      console.log(this.goodCateList);
    },
    //级联选择器反生改变之后的回调函数
    cascaderHandleChange() {
      // 用IF判断语句强制用户只能选择三级选项
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },
    //监听标签页切换的钩子函数
    tabsBeforeLeave(activeName, oldActiveName) {
      //如果当前标签页是0，同时级联选择器没有选择，那就不允许跳转
      if (oldActiveName == 0 && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请先选择分类");
        return false;
      }
      return true;
    },
    // 标签页点击是触发的函数
    async tabsClick() {
      // 商品动态参数页面请求
      if (this.activeIndex === "1") {
        const res = await getAttrList(`categories/${this.cateId}/attributes`, {
          sel: "many",
        });
        if (res.meta.status != 200) return this.$message.error(res.meta.msg);
        console.log(res);
        this.manyAttrList = res.data;
        this.manyAttrList.forEach((item, index) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
        });
      }
      //商品静态属性参数请求
      else if (this.activeIndex === "2") {
        const res = await getAttrList(`categories/${this.cateId}/attributes`, {
          sel: "only",
        });
        if (res.meta.status != 200) return this.$message.error(res.meta.msg);
        this.onlyAttrList = res.data;
      }
    },
    // 图片上传页面相关事件
    // 点图片名字的预览事件
    upLoadLandlePreview(file) {
      console.log(file);
      // 获得图片预览的url地址
      this.preUrl = file.response.data.url;
      // 弹出对话框
      this.isPicDialogVisible = true;
    },
    // 移除图片触发的事件
    upLoadLandleRemove(file) {
      // 1.根据信息找到数组里的那一项
      const index = this.addForm.pics.findIndex(
        (item) => item.pic == file.response.data.tmp_path
      );
      // 2.从数组里把他删除
      this.addForm.pics.splice(index, 1);
    },
    // 上传图片成功的回调函数，可接受返回参数
    uploadSuccessRespoonse(res) {
      // 1.拼接图片路径信息
      const picInfo = {
        pic: res.data.tmp_path,
      };
      // 2把图片信息push到上传资料里
      this.addForm.pics.push(picInfo);
    },
    // 添加商品网络请求
    addGoods() {
      // 表单预验证
      this.$refs.addFormRef.validate(async (boolean, obj) => {
        // 判断是否校验通过
        console.log(this.addForm.goods_cat);
        if (!boolean) {
          return this.$message.error("请填写必要的表单项目");
        }
        // 通过之后发起真正的请求请求
        // 由于上传数据中心的goods_cat的数据类型是字符串，所以要转换addForm里的goods_cat,但是一旦转换之后就会和级联选择器的要求发生冲突，解决方案就是深拷贝一个addFrom用来上传数据
        //深拷贝采用但三方插件ladash
        const addFormDeep = _.cloneDeep(this.addForm);
        addFormDeep.goods_cat = addFormDeep.goods_cat.join(",");
        console.log(this.manyAttrList);
        console.log(this.onlyAttrList);
        // 处理动态参数
        this.manyAttrList.forEach((item) => {
          const attr = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.addForm.attrs.push(attr);
        });
        //处理静态参数
        this.onlyAttrList.forEach((item) => {
          const attr = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.addForm.attrs.push(attr);
        });
        addFormDeep.attrs = this.addForm.attrs
        console.log(addFormDeep);
        // 发送添加请求
        const res = await addgood(addFormDeep)
         if (res.meta.status != 201) return this.$message.error(res.meta.msg);
         this.$message.success(res.meta.msg);
         this.$router.push('/goods')

      });
    },
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    },
  },
};
</script>

<style  scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  width: 480px;
}
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-checkbox {
  margin-right: 10px !important;
}
</style>
